package ro.fortech.peaa.view;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;

import org.springframework.web.servlet.view.xslt.AbstractXsltView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import ro.fortech.peaa.domain.Job;
/**
 * View for new employee page.
 * 
 * @author robert
 *
 */

@SuppressWarnings("deprecation")
public class EmployeeNewView extends AbstractXsltView {
	@SuppressWarnings("unchecked")
	public Source createXsltSource(Map model, String rootName, HttpServletRequest
			request, HttpServletResponse response) {

		Document document = null;
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			return null;
		}
		Element root = document.createElement(rootName);
		logger.info(rootName);
			
		String errorMessage = (String) model.get("error_message");
		if (errorMessage == null) {
			errorMessage = "";
		}
		Element errorMessageNode = document.createElement("error_message");
		Text errorMessageText = document.createTextNode(errorMessage);
		errorMessageNode.appendChild(errorMessageText);
		root.appendChild(errorMessageNode);
		
		Element jobsNode = document.createElement("jobs");
        List<Job> jobs = (List<Job>) model.get("jobs");
        logger.info("there are " + jobs.size() + " jobs");
        logger.info(rootName);
	    for (Iterator<Job> it = jobs.iterator(); it.hasNext();) {
	        Job nextJob = (Job) it.next();
	        Element jobNode = document.createElement("job");
	        
	        // job id
	        Element idNode = document.createElement("id");
	        Text textNode = document.createTextNode(nextJob.getId());
	        idNode.appendChild(textNode);
	        jobNode.appendChild(idNode);
	        
	        // job title
	        Element titleNode = document.createElement("title");
	        textNode = document.createTextNode(nextJob.getTitle());
	        titleNode.appendChild(textNode);
	        jobNode.appendChild(titleNode);
	        
	        jobsNode.appendChild(jobNode);
	    }
        root.appendChild(jobsNode);
	    
        Source result = new DOMSource(root);
	    return result;
	}
}
